<template>
  <v-dialog
    v-model="visible"
    width="auto"
  >
    <v-card title="酷狗登录" subtitle="打开手机酷狗音乐,扫一扫登录">
      <v-card-text class="flex-cc">
        <div class="w-40 h-40 relative">
          <img class="wh-full" :src="qrcodeImg" />
          <div
            v-if="qrcodeStatus!=-1&&qrcodeStatus!=1"
            class="wh-full abso-lt flex-col flex-cc bg-light bg-opacity-80 text-sm"
          >
            <template v-if="qrcodeStatus==0">
              <div>二维码已失效</div>
              <div class="flex-cc mt-1">
                <v-btn size="x-small" elevation="1" @click="init">点击刷新</v-btn>
              </div>
            </template>
            <template v-if="qrcodeStatus==2">
              <div>已扫码</div>
              <div>请在手机上确认登录</div>
            </template>
          </div>
        </div>
      </v-card-text>
      <v-card-actions>
        <v-btn color="primary" block @click="visible=false">关闭</v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<script lang="ts" setup>
import {ref,watch} from 'vue';
import {getLoginQrCode,checkQrCode,loginByToken} from '@/apis/kgApi';
import {useVModel} from '@/hooks/useVModel';
import { useUserStore } from '@/stores/user';
import { message } from '@/utils/message';

const props=defineProps<{
  modelValue:boolean
}>()
const emit=defineEmits<{
  (e: 'update:modelValue'): void;
}>()

const userStore=useUserStore();
const qrcode=ref(''),qrcodeImg=ref(''),qrcodeStatus=ref(-1);
const visible=useVModel(props,'modelValue',emit);
let timeId:any=0;

watch(visible,(val) =>{
  if(val){
    init()
  }else{
    clearInterval(timeId);
    qrcodeImg.value='';
    qrcodeStatus.value=-1;
    qrcode.value='';
  }
})
const init=async () =>{
  const qrData=await getLoginQrCode();
  qrcode.value=qrData.qrcode;
  qrcodeImg.value=qrData.qrcode_img;
  timeId=setInterval(async () =>{
    if(!qrcode.value) return;
    const chData=await checkQrCode(qrcode.value);
    qrcodeStatus.value=chData.status;
    //console.log(chData)
    if([0,4].includes(qrcodeStatus.value)){
      clearInterval(timeId);
    }
    if(qrcodeStatus.value==4){
      userStore.login({
        id:chData.userid,
        name:chData.nickname,
        avatar:chData.pic
      },chData.token)
      visible.value=false;
      loginByToken();
      message('success','登录成功');
    }
  },3000)
}
</script>

<style scoped>

</style>